/**
 * 统一设置系统配置
 * 整合所有设置相关的配置和常量
 */

import { merge } from 'lodash-es'

// 环境检测函数
const isDev = import.meta.env.DEV
const isProd = import.meta.env.PROD
const isTest = import.meta.env.MODE === 'test'

// 统一设置接口定义
export interface UnifiedSettings {
  // 主题设置
  theme: {
    mode: 'light' | 'dark' | 'auto'
    primaryColor: string
    borderRadius: 'none' | 'small' | 'medium' | 'large'
  }
  
  // 界面设置
  interface: {
    sidebarCollapsed: boolean
    sidebarMode: 'vertical' | 'horizontal' | 'mix'
    headerHeight: number
    footerHeight: number
    pageSize: number
    showBreadcrumb: boolean
    showTabs: boolean
    showLogo: boolean
  }
  
  // 语言设置
  language: {
    locale: string
    fallbackLocale: string
    availableLocales: string[]
  }
  
  // 通知设置
  notification: {
    enableSound: boolean
    enableDesktop: boolean
    enableEmail: boolean
    enableSms: boolean
    soundVolume: number
    notificationTypes: {
      system: boolean
      security: boolean
      business: boolean
      marketing: boolean
    }
  }
  
  // 安全设置
  security: {
    sessionTimeout: number // 分钟
    maxLoginAttempts: number
    passwordExpiry: number
    twoFactorAuth: boolean
    ipWhitelist: string[]
    loginLogRetention: number
    passwordMinLength: number
    passwordMaxLength: number
  }
  
  // 性能设置
  performance: {
    enableCache: boolean
    cacheExpiry: number
    enableCompression: boolean
    enableLazyLoad: boolean
    maxConcurrentRequests: number
    requestTimeout: number
  }
  
  // 系统设置
  system: {
    systemName: string
    systemVersion: string
    systemDescription: string
    systemLogo: string
    systemFavicon: string
    copyright: string
    icp: string
    enableRegistration: boolean
    enableGuestAccess: boolean
    maintenanceMode: boolean
  }
  
  // 数据设置
  data: {
    dataRetention: number
    backupFrequency: 'daily' | 'weekly' | 'monthly'
    backupRetention: number
    enableAutoBackup: boolean
    backupLocation: string
    enableDataExport: boolean
    enableDataImport: boolean
  }
  
  // 集成设置
  integration: {
    enableApi: boolean
    apiRateLimit: number
    enableWebhook: boolean
    webhookUrl: string
    enableSso: boolean
    ssoProvider: string
    enableOauth: boolean
    oauthProviders: string[]
  }
  
  // 验证码设置
  captcha: {
    enabled: boolean
    length: number
    refreshOnError: boolean
  }
  
  // 登录设置
  login: {
    rememberMeEnabled: boolean
    autoLoginEnabled: boolean
    maxLoginAttempts: number
  }
}

// 设置分类定义
export interface SettingsCategory {
  key: keyof UnifiedSettings
  title: string
  description: string
  icon: string
  order: number
  enabled: boolean
}

// 默认设置
const defaultSettings: UnifiedSettings = {
  theme: {
    mode: 'light',
    primaryColor: '#409EFF',
    borderRadius: 'medium'
  },
  interface: {
    sidebarCollapsed: false,
    sidebarMode: 'vertical',
    headerHeight: 60,
    footerHeight: 40,
    pageSize: 10,
    showBreadcrumb: true,
    showTabs: true,
    showLogo: true
  },
  language: {
    locale: 'zh-cn',
    fallbackLocale: 'en',
    availableLocales: ['zh-cn', 'en']
  },
  notification: {
    enableSound: true,
    enableDesktop: true,
    enableEmail: false,
    enableSms: false,
    soundVolume: 50,
    notificationTypes: {
      system: true,
      security: true,
      business: false,
      marketing: false
    }
  },
  security: {
    sessionTimeout: 30,
    maxLoginAttempts: 5,
    passwordExpiry: 90,
    twoFactorAuth: false,
    ipWhitelist: [],
    loginLogRetention: 365,
    passwordMinLength: 6,
    passwordMaxLength: 20
  },
  performance: {
    enableCache: true,
    cacheExpiry: 3600,
    enableCompression: true,
    enableLazyLoad: true,
    maxConcurrentRequests: 10,
    requestTimeout: 30000
  },
  system: {
    systemName: 'Convallaria',
    systemVersion: '1.0.0',
    systemDescription: '企业级管理平台',
    systemLogo: '/logo.svg',
    systemFavicon: '/favicon.ico',
    copyright: '© 2024 Convallaria. All rights reserved.',
    icp: '',
    enableRegistration: false,
    enableGuestAccess: false,
    maintenanceMode: false
  },
  data: {
    dataRetention: 2555,
    backupFrequency: 'daily',
    backupRetention: 30,
    enableAutoBackup: true,
    backupLocation: '/backups',
    enableDataExport: true,
    enableDataImport: true
  },
  integration: {
    enableApi: true,
    apiRateLimit: 1000,
    enableWebhook: false,
    webhookUrl: '',
    enableSso: false,
    ssoProvider: '',
    enableOauth: false,
    oauthProviders: []
  },
  captcha: {
    enabled: true,
    length: 4,
    refreshOnError: true
  },
  login: {
    rememberMeEnabled: true,
    autoLoginEnabled: false,
    maxLoginAttempts: 5
  }
}

// 环境特定配置
const devSettings: Partial<UnifiedSettings> = {
  captcha: {
    enabled: true,
    length: 4,
    refreshOnError: true
  },
  security: {
    sessionTimeout: 60,
    maxLoginAttempts: 5,
    passwordExpiry: 90,
    twoFactorAuth: false,
    ipWhitelist: [],
    loginLogRetention: 365,
    passwordMinLength: 4,
    passwordMaxLength: 10
  }
}

const prodSettings: Partial<UnifiedSettings> = {
  captcha: {
    enabled: true,
    length: 4,
    refreshOnError: true
  },
  security: {
    sessionTimeout: 30,
    maxLoginAttempts: 5,
    passwordExpiry: 90,
    twoFactorAuth: false,
    ipWhitelist: [],
    loginLogRetention: 365,
    passwordMinLength: 6,
    passwordMaxLength: 20
  }
}

const testSettings: Partial<UnifiedSettings> = {
  captcha: {
    enabled: false,
    length: 4,
    refreshOnError: false
  },
  login: {
    rememberMeEnabled: false,
    autoLoginEnabled: false,
    maxLoginAttempts: 5
  },
  security: {
    sessionTimeout: 10,
    maxLoginAttempts: 5,
    passwordExpiry: 90,
    twoFactorAuth: false,
    ipWhitelist: [],
    loginLogRetention: 365,
    passwordMinLength: 4,
    passwordMaxLength: 10
  }
}

// 设置分类配置
export const SETTINGS_CATEGORIES: SettingsCategory[] = [
  { key: 'theme', title: '主题外观', description: '自定义界面主题和颜色', icon: 'Brush', order: 1, enabled: true },
  { key: 'interface', title: '界面设置', description: '配置界面布局和显示选项', icon: 'Monitor', order: 2, enabled: true },
  { key: 'language', title: '语言设置', description: '设置界面语言和本地化', icon: 'Flag', order: 3, enabled: true },
  { key: 'notification', title: '通知设置', description: '配置通知方式和类型', icon: 'Bell', order: 4, enabled: true },
  { key: 'security', title: '安全设置', description: '配置安全策略和权限', icon: 'Lock', order: 5, enabled: true },
  { key: 'performance', title: '性能设置', description: '优化系统性能和缓存', icon: 'Setting', order: 6, enabled: true },
  { key: 'system', title: '系统设置', description: '系统基本信息和配置', icon: 'Tools', order: 7, enabled: true },
  { key: 'data', title: '数据设置', description: '数据管理和备份配置', icon: 'Folder', order: 8, enabled: true },
  { key: 'integration', title: '集成设置', description: '第三方服务和API配置', icon: 'Connection', order: 9, enabled: true },
  { key: 'captcha', title: '验证码设置', description: '验证码相关配置', icon: 'Shield', order: 10, enabled: true },
  { key: 'login', title: '登录设置', description: '登录相关配置', icon: 'User', order: 11, enabled: true }
]

// 根据环境合并配置
let currentSettings: UnifiedSettings = defaultSettings

if (isDev) {
  currentSettings = merge({}, defaultSettings, devSettings)
} else if (isProd) {
  currentSettings = merge({}, defaultSettings, prodSettings)
} else if (isTest) {
  currentSettings = merge({}, defaultSettings, testSettings)
}

export const unifiedSettings = currentSettings

// 配置验证函数
export function validateUnifiedSettings(settings: UnifiedSettings): { valid: boolean; errors: string[] } {
  const errors: string[] = []

  // 验证主题设置
  if (!['light', 'dark', 'auto'].includes(settings.theme.mode)) {
    errors.push('主题模式必须是 light、dark 或 auto')
  }
  
  if (!/^#[0-9A-Fa-f]{6}$/.test(settings.theme.primaryColor)) {
    errors.push('主色调必须是有效的十六进制颜色值')
  }
  
  if (!['none', 'small', 'medium', 'large'].includes(settings.theme.borderRadius)) {
    errors.push('圆角大小必须是 none、small、medium 或 large')
  }

  // 验证界面设置
  if (!['vertical', 'horizontal', 'mix'].includes(settings.interface.sidebarMode)) {
    errors.push('侧边栏模式必须是 vertical、horizontal 或 mix')
  }
  
  if (![10, 20, 50, 100].includes(settings.interface.pageSize)) {
    errors.push('页面大小必须是 10、20、50 或 100')
  }

  // 验证语言设置
  if (!settings.language.availableLocales.includes(settings.language.locale)) {
    errors.push('界面语言必须在可用语言列表中')
  }

  // 验证通知设置
  if (settings.notification.soundVolume < 0 || settings.notification.soundVolume > 100) {
    errors.push('音量大小必须在 0-100 之间')
  }

  // 验证安全设置
  if (settings.security.sessionTimeout < 5 || settings.security.sessionTimeout > 1440) {
    errors.push('会话超时时间必须在 5-1440 分钟之间')
  }
  
  if (settings.security.maxLoginAttempts < 1) {
    errors.push('最大登录尝试次数必须大于 0')
  }
  
  if (settings.security.passwordMinLength < 4 || settings.security.passwordMinLength > 20) {
    errors.push('密码最小长度必须在 4 到 20 之间')
  }
  
  if (settings.security.passwordMaxLength < settings.security.passwordMinLength || settings.security.passwordMaxLength > 30) {
    errors.push('密码最大长度必须合理且不大于 30')
  }

  // 验证验证码设置
  if (settings.captcha.length < 2 || settings.captcha.length > 6) {
    errors.push('验证码长度必须在 2 到 6 之间')
  }

  // 验证性能设置
  if (settings.performance.cacheExpiry < 60 || settings.performance.cacheExpiry > 86400) {
    errors.push('缓存过期时间必须在 60-86400 秒之间')
  }
  
  if (settings.performance.maxConcurrentRequests < 1 || settings.performance.maxConcurrentRequests > 50) {
    errors.push('最大并发请求数必须在 1-50 之间')
  }

  return {
    valid: errors.length === 0,
    errors
  }
}

// 获取设置值
export function getSettingValue(settings: UnifiedSettings, path: string): unknown {
  const keys = path.split('.')
  let current: unknown = settings
  
  for (const key of keys) {
    if (current && typeof current === 'object' && key in current) {
      current = (current as Record<string, unknown>)[key]
    } else {
      return undefined
    }
  }
  
  return current
}

// 设置值
export function setSettingValue(settings: UnifiedSettings, path: string, value: unknown): void {
  const keys = path.split('.')
  let current: Record<string, unknown> = settings as Record<string, unknown>
  
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i]
    if (!current[key] || typeof current[key] !== 'object') {
      current[key] = {}
    }
    current = current[key] as Record<string, unknown>
  }
  
  current[keys[keys.length - 1]] = value
}

// 合并设置
export function mergeSettings(target: UnifiedSettings, source: Partial<UnifiedSettings>): UnifiedSettings {
  return merge({}, target, source)
}

// 重置设置
export function resetSettings(category?: keyof UnifiedSettings): UnifiedSettings {
  if (category) {
    return { ...defaultSettings, [category]: defaultSettings[category] }
  }
  return { ...defaultSettings }
}
